package com.rchat.pocmini.wxapi;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * Created by ljd on 2017/2/13.
 *
 * 微信支付常量及工具
 */

public class Constants {
    //App id
    public static final String APP_ID = "wxecc8fd708d1b4c51";
    //商户号id
    public static final String PARTNER_ID = "1439963402";
    //package
    public static final String PACKAGE = "Sign=WXPay";
    //签名key
    public static final String APP_KEY = "7fd6ec3199e752b32dadec9ffcfda2e7";

    public static class ShowMsgActivity {
        public static final String STitle = "showmsg_title";
        public static final String SMessage = "showmsg_message";
        public static final String BAThumbData = "showmsg_thumb_data";
    }

    /**
     * 时间戳
     * @return System.currentTimeMillis() / 1000
     */
    public static String genTimeStamp() {
        return System.currentTimeMillis() / 1000 + "";
    }

    /**
     * 获取IP地址
     * @return
     */
    public static String getIp() {
        try {
            for (Enumeration<NetworkInterface> enNetI = NetworkInterface
                    .getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
                NetworkInterface netI = enNetI.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = netI
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 生成微信支付sign
     * @param params 参数map
     * @return signString
     */
    public static String createSign(SortedMap<Object,Object> params){
        StringBuilder sb = new StringBuilder();
        Set set = params.entrySet();//升序
        for (Object aSet : set) {
            Map.Entry entry = (Map.Entry) aSet;
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !".".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=" + Constants.APP_KEY);
        return MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
    }

    /**
     * 将金额转换成分
     * @param fee 元格式的
     * @return 分
     */
    public static String changeToFen(Double fee){
        String priceStr = "";
        if(fee != null){
            int p = (int)(fee * 100); //价格变为分
            priceStr = Integer.toString(p);
        }
        return priceStr;
    }
}
